package cn.cuilan.jol;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;

/**
 * 偏向锁示例
 *
 * @author zhang.yan
 * @since 2021/3/8
 */
public class BiasedLockTest {

    // unused:25             hashcoed:31         unused:1 age:4 b_lock:1 lock:2
    // 初始化
    // 0000000000000000000000000 0000000000000000000000000000000 0 0000 0 01
    // 偏向锁
    // 000000000000000001111111101101111111111100000001000110 00 0 0000 1 01
    // 轻量级
    // 00000000000000000111000000000000000001000010100001101001101110 00
    // 重量级
    // 00000000000000000111111111101100100100100000000101110001111010 10
    public static void main(String[] args) throws InterruptedException {

        System.out.println(VM.current().details());

        // 偏向锁启动默认4秒后生效，或添加启动参数：-XX:BiasedLockingStartupDelay=0
        Thread.sleep(5000L);

        final A a = new A();
        ClassLayout layout = ClassLayout.parseInstance(a);

        System.out.println("创建对象");
        System.out.println(layout.toPrintable());

        synchronized (a) {
            System.out.println("同步代码块");
            System.out.println(layout.toPrintable());
        }

//        System.gc();
        Thread.sleep(1000L);

        System.out.println("同步代码块执行完成");
        System.out.println(layout.toPrintable());

        Thread t = new Thread(() -> {
            synchronized (a) {
                System.out.println("t同步代码块");
                System.out.println(layout.toPrintable());
            }
        });
        t.start();

        Thread.sleep(1000L);

        synchronized (a) {
            System.out.println("同步代码块");
            System.out.println(layout.toPrintable());
        }

        System.gc();

        System.out.println("t同步代码块执行完成");
        System.out.println(layout.toPrintable());

    }

}
